<template>
  <el-container class="hp-handler-body">
    <el-header class="hp-handler-header">
      <el-card shadow="never">
        <div class="hp-flow-title">
          {{ (flowInfo.processInfo && flowInfo.processInfo.name) ? flowInfo.processInfo.name : '朱秋柏提交的售后工单' }}
          <div v-if="flowInfo.processInfo && flowInfo.processInfo.status=='COMPLETE'" class="hp-flow-status-complate">
            完成
          </div>
          <div v-if="flowInfo.processInfo && flowInfo.processInfo.status=='ACTIVE'" class="hp-flow-status-active">
            进行中
          </div>
          <div v-if="flowInfo.processInfo && flowInfo.processInfo.status=='CANCEL'" class="hp-flow-status-cancel">
            已取消
          </div>
          <div v-if="flowInfo.processInfo && flowInfo.processInfo.status=='PRE'" class="hp-flow-status-pre">发起中</div>
        </div>
        <div class="hp-flow-info" id="flowInfoDiv">
          <span
              v-if="flowInfo.processInfo && flowInfo.processInfo.startTime"><b>开始时间：</b>{{
              flowInfo.processInfo.startTime
            }}</span>
          <span
              v-if="flowInfo.processInfo && flowInfo.processInfo.endTime"><b>结束时间：</b>{{
              flowInfo.processInfo.startTime
            }}</span>
          <span v-if="flowInfo.processInfo && flowInfo.processInfo.duration">
              <b v-if="flowInfo.processInfo && (flowInfo.processInfo.status=='COMPLETE' || flowInfo.processInfo.status=='CANCEL')">总耗时：</b>
              <b v-else>已耗时：</b>
              {{ flowInfo.processInfo.duration }}</span>
        </div>
        <div class="hp-flow-button">
          <el-tooltip :content="buttons.approve.label+'当前任务节点的信息，流程将流转到下一个节点执行'"
                      placement="bottom" effect="light">
            <el-button v-show="approveShow()" size="small" type="success" @click="handlerApprove" class="hiss-handler-button hiss-approve">
              <Stamp :size="14"/>
              {{ buttons.approve.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="buttons.reject.label+'当前任务节点的信息'" placement="bottom" effect="light">
            <el-button v-show="rejectShow()" size="small" type="success" @click="handlerReject" class="hiss-handler-button hiss-reject">
              <XCircle :size="14"/>
              {{ buttons.reject.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="buttons.rollback.label+'当前任务，并回退到之前任意节点'" placement="bottom"
                      effect="light">
            <el-button v-show="rollbackShow()" size="small" type="success" @click="handlerRollback" class="hiss-handler-button hiss-rollback">
              <EyeOff :size="14"/>
              {{ buttons.rollback.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="'把当前任务'+buttons.delegate.label+'给另外一个用户审批'" placement="bottom"
                      effect="light">
            <el-button v-show="delegateShow()" size="small" type="success" @click="handlerDelegate" class="hiss-handler-button hiss-delegate">
              <Figma :size="14"/>
              {{ buttons.delegate.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip content="把当前信息转给另外一个人查看" placement="bottom" effect="light">
            <el-button v-show="ccShow()" size="small" type="success" @click="handlerCc" class="hiss-handler-button hiss-cc">
              <CreativeCommons :size="14"/>
              {{ buttons.cc.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip content="把当前信息转给另外一个人查看，需要他人知晓" placement="bottom" effect="light">
            <el-button v-show="notificationShow()" size="small" type="success" @click="handlerNotification" class="hiss-handler-button hiss-notification">
              <XCircle :size="14"/>
              {{ buttons.notification.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="'对于'+buttons.notification.label+'的信息进行知晓处理'" placement="bottom"
                      effect="light">
            <el-button v-show="readShow()" size="small" type="success" @click="handlerRead" class="hiss-handler-button hiss-read">
              <UserPlus :size="14"/>
              {{ buttons.read.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="'多人审批时，'+buttons.claim.label+'一个未分配的任务'" placement="bottom" effect="light">
            <el-button v-show="claimShow()" size="small" type="success" @click="handlerClaim" class="hiss-handler-button hiss-claim">
              <CornerUpLeft :size="14"/>
              {{ buttons.claim.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="'多人审批时，'+buttons.unclaim.label+'一个任务'" placement="bottom" effect="light">
            <el-button v-show="unclaimShow()" size="small" type="success" @click="handlerUnclaim" class="hiss-handler-button hiss-unclaim">
              <CornerUpRight :size="14"/>
              {{ buttons.unclaim.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip content="把当前任务转给另一人，审批之后当前人再审批" placement="bottom" effect="light">
            <el-button v-show="beforeSignShow()" size="small" type="warning" @click="handlerBeforeSign" class="hiss-handler-button hiss-before-sign">
              <UserPlus :size="14"/>
              {{ buttons.before_sign.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip content="当前审批人审批后，还要加签的人审批" placement="bottom" effect="light">
            <el-button v-show="afterSignShow()" size="small" type="warning" @click="handlerAfterSign" class="hiss-handler-button hiss-after-sign">
              <UserPlus :size="14"/>
              {{ buttons.after_sign.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip content="当前并行审批人员中加签新的人审批" placement="bottom" effect="light">
            <el-button v-show="parallelSignShow()" size="small" type="warning" @click="handlerParallelSign" class="hiss-handler-button hiss-parallel-sign">
              <UserPlus :size="14"/>
              {{ buttons.parallel_sign.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="buttons.jump.label+'当前流程节点中任意节点'" placement="bottom" effect="light">
            <el-button v-show="jumpShow()" size="small" type="success" @click="handlerJump" class="hiss-handler-button hiss-jump">
              <RedoDot :size="14"/>
              {{ buttons.jump.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="buttons.trigger.label+'流程的事件、信号'" placement="bottom" effect="light">
            <el-button v-show="triggerShow()" size="small" type="success" @click="handlerTrigger" class="hiss-handler-button hiss-trigger">
              <Euro :size="14"/>
              {{ buttons.trigger.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="buttons.send.label+'流程给下一个人办理，既发起流程'" placement="bottom" effect="light">
            <el-button size="small" v-show="sendShow()" @click="handlerFormSend" type="danger" class="hiss-handler-button hiss-send">
              <Send :size="14"/>
              {{ buttons.send.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="buttons.draft.label+'只保存数据，不发起流程'" placement="bottom" effect="light">
            <el-button size="small" v-show="draftShow()" @click="handlerFormDraft" type="info" warning plain class="hiss-handler-button hiss-draft">
              <Save :size="14"/>
              {{ buttons.draft.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="buttons.submit.label+'-重新提交表单数据，并发起审批'" placement="bottom" effect="light">
            <el-button size="small" v-show="submitShow()" @click="handlerActionSubmit" type="danger" warning plain class="hiss-handler-button hiss-submit">
              <Crop :size="14"/>
              {{ buttons.submit.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="buttons.cancel.label+'一个任务'" placement="bottom" effect="light">
            <el-button v-show="cancelShow()" size="small" type="success" @click="handlerCancel" class="hiss-handler-button hiss-cancel">
              <Delete :size="14"/>
              {{ buttons.cancel.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="'发起人'+buttons.withdraw.label+'发起的流程'" placement="bottom" effect="light">
            <el-button v-show="withdrawShow()" size="small" type="success" @click="handlerWithdraw" class="hiss-handler-button bg-gradient1 hiss-withdraw">
              <Scaling :size="14"/>
              {{ buttons.withdraw.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="'发起人'+buttons.expedite.label+'当前办理人'" placement="bottom" effect="light">
            <el-button v-show="expediteShow()" size="small" type="success" @click="handlerActionExpedite" class="hiss-handler-button bg-gradient1 hiss-expedite">
              <AlarmCheck :size="14"/>
              {{ buttons.expedite.label }}
            </el-button>
          </el-tooltip>
          <el-tooltip :content="'重新发起该流程'" placement="bottom" effect="light">
            <el-button v-show="restartShow()" size="small" type="success" @click="handlerActionRestart" class="hiss-handler-button bg-gradient1 hiss-restart">
              <ArrowUpRightFromCircle :size="14"/>
              {{ buttons.restart.label }}
            </el-button>
          </el-tooltip>
        </div>
      </el-card>
    </el-header>
    <el-main class="hp-main-body">
      <el-tabs type="border-card" id="tabAreaDiv" class="hp-tab-area" v-model="tabName" @tab-change="handleTabChange">
        <el-tab-pane class="hp-pane-body" v-for="(item,index) in formList" :key="viewerProcessId+'-t-'+index" :name="'form'+index">
          <template #label>
              <span>
                <el-icon v-if="item.hasEdit" size="18" style="color: red"><Edit /></el-icon>
                <el-icon v-else size="18"><View /></el-icon>
                <span>{{ item.formName }}</span>
              </span>
          </template>
          <el-card class="box-card hp-form-card" shadow="never">
            <FormDesign :ref="'formDataArea'+index" :key="item.dataId+refreshComponentKey+'d-'+index" :current-route-path="currentRoutePath" :formData="item"/>
          </el-card>
          <el-card class="box-card hp-comment-card" shadow="hover" style="text-align: left">
            <el-empty description="暂无评论信息" v-if="!flowInfo.comments||flowInfo.comments.length==0"/>
            <el-timeline>
              <el-timeline-item
                  v-for="(comment, index) in flowInfo.comments"
                  :key="index"
                  :timestamp="formattedDate(comment.time)"
                  placement="top">
                <el-card class="hp-comment-item" shadow="hover" :body-style="{ border:'none',padding:'5px' }">
                  <h4 v-html="comment.message"></h4>
                  <p v-html="comment.fullMsg"></p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </el-tab-pane>
        <el-tab-pane name="flow" class="hp-pane-body">
          <template #label>
              <span>
                <el-icon size="18"><Operation/></el-icon>
                <span>流程</span>
              </span>
          </template>
          <ViewerDev v-if="getMode()=='DEV'" :flow="this.flowInfo" :process-id="viewerProcessId" :key="viewerProcessId" ref="viewer" :flowDataNotice="flowDataNotice"/>
          <ViewerBis v-if="getMode()=='BIS'" :flow="this.flowInfo" :process-id="viewerProcessId" :key="viewerProcessId" ref="viewer" :flowDataNotice="flowDataNotice"/>
        </el-tab-pane>
      </el-tabs>
    </el-main>
  </el-container>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.approve.label" name="approve" ref="approve"
                 :field-label="buttons.approve.label+'意见'" field-name="reason" :flowInfo="flowInfo"
                 :fun="handlerActionApprove" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.reject.label" name="reject" ref="reject"
                 :field-label="buttons.reject.label+'意见'" field-name="reason" :flowInfo="flowInfo"
                 :fun="handlerActionReject" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.notification.label" name="notification"
                 ref="notification" :field-label="buttons.notification.label+'人'" field-name="userName"
                 :flowInfo="flowInfo" :fun="handlerActionNotification" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.cc.label" name="cc" ref="cc"
                 :field-label="buttons.cc.label+'人'" field-name="userName" :flowInfo="flowInfo"
                 :fun="handlerActionCc" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.before_sign.label" name="beforeSign" ref="beforeSign"
                 field-label="加签人" field-name="userName" :flowInfo="flowInfo"
                 :fun="handlerActionBeforeSign" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.after_sign.label" name="afterSign" ref="afterSign"
                 field-label="加签人" field-name="userName" :flowInfo="flowInfo"
                 :fun="handlerActionAfterSign" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.parallel_sign.label" name="parallelSign"
                 ref="parallelSign" field-label="加签人" field-name="userName" :flowInfo="flowInfo"
                 :fun="handlerActionParallelSign"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.delegate.label" name="delegate" ref="delegate"
                 :field-label="buttons.delegate.label+'人'" field-name="userName" :flowInfo="flowInfo"
                 :fun="handlerActionDelegate" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.rollback.label" name="rollback" ref="rollback"
                 :field-label="buttons.rollback.label+'原因'" field-name="reason" :flowInfo="flowInfo"
                 :fun="handlerActionRollback" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.jump.label" name="jump" ref="jump"
                 :field-label="buttons.jump.label+'原因'" field-name="reason" :flowInfo="flowInfo"
                 :fun="handlerActionJump" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.withdraw.label" name="withdraw" ref="withdraw"
                 :field-label="buttons.withdraw.label+'原因'" field-name="reason" :flowInfo="flowInfo"
                 :fun="handlerActionWithdraw" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.read.label" name="read" ref="read" field-label=""
                 field-name="" :variable="false" :flowInfo="flowInfo" :fun="handlerActionRead" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.claim.label" name="claim" ref="claim" field-label=""
                 field-name="" :variable="false" :flowInfo="flowInfo" :fun="handlerActionClaim" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.unclaim.label" name="unclaim" ref="unclaim"
                 field-label="" field-name="" :variable="false" :flowInfo="flowInfo"
                 :fun="handlerActionUnclaim" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.cancel.label" name="cancel" ref="cancel"
                 :field-label="buttons.cancel.label+'原因'" field-name="reason" :variable="false" :flowInfo="flowInfo"
                 :fun="handlerActionCancel" :integration="integration"></OperateDialog>
  <OperateDialog :refreshData="refreshData" :buttonName="buttons.trigger.label" name="trigger" ref="trigger"
                 :field-label="buttons.trigger.label+'代码'" field-name="name" :variable="false" :flowInfo="flowInfo"
                 :fun="handlerActionTrigger" :integration="integration"></OperateDialog>
</template>
<script>
import {
  ArrowUpRightFromCircle,
  AlarmCheck,
  Crop,
  RedoDot,
  FormInput,
  Euro,
  Stamp,
  ReplyAll,
  XCircle,
  EyeOff,
  Figma,
  Reply,
  Send,
  UserPlus,
  Radio,
  Save,
  CornerUpLeft,
  CornerUpRight,
  CreativeCommons,
  Delete,
  Scaling
} from 'lucide-vue-next';
import OperateDialog from './OperateDialog'
import ViewerBis from '../ViewerBis'
import ViewerDev from '../ViewerDev'
import FormDesign from './FormDesign'
import User from '@/utils/user'
import {
  processActionBeforeSign,
  processActionTrigger,
  processActionAfterSign,
  processActionWithdraw,
  processActionJump,
  processActionCancel,
  processActionApprove,
  processActionNotification,
  processActionReject,
  processActionCc,
  processActionRollback,
  processActionDelegate,
  processActionUnclaim,
  processActionClaim,
  processActionRead,
  handlerActionParallelSign,
  processActionDraft,
  processActionSend,
  processActionSubmit,
  processActionExpedite,
  processActionRestart
} from "@/api/DevForDesignApi";

let vueApp;
export default {
  components: {
    ArrowUpRightFromCircle,
    AlarmCheck,
    FormDesign,
    Euro,
    Crop,
    RedoDot,
    OperateDialog,
    FormInput,
    ViewerBis,
    ViewerDev,
    Stamp,
    ReplyAll,
    XCircle,
    EyeOff,
    Figma,
    Reply,
    Send,
    UserPlus,
    Radio,
    Save,
    CornerUpLeft,
    CornerUpRight,
    CreativeCommons,
    Delete,
    Scaling
  },
  props: {
    processId: {
      type: String,
      default: null
    },
    mode: {
      type: String,
      default: 'DEV'
    },
    integration:{
      type:Boolean,
      default: false
    },
    currentRoutePath: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      refreshComponentKey : '',
      viewerProcessId:'',//初始化的流程id
      tabName: 'form0',//标签类型
      config: {},// 页面配置json
      hasEdit: false,// 当前流程是否存在编辑数据的行为
      isCandidate: false,// 是否是候选办理人
      flowInfo: {//流程信息
        processInfo: {
          status: 'ACTIVE',
          name: ''
        }
      },
      buttons: {// 页面上的按钮配置
        approve: {
          show: true,
          label: '同意'
        },
        reject: {
          show: true,
          label: '不同意'
        },
        rollback: {
          show: true,
          label: '驳回'
        },
        delegate: {
          show: true,
          label: '委派'
        },
        cc: {
          show: true,
          label: '抄送'
        },
        notification: {
          show: true,
          label: '知会'
        },
        claim: {
          show: true,
          label: '认领'
        },
        unclaim: {
          show: true,
          label: '归还'
        },
        cancel: {
          show: true,
          label: '取消'
        },
        submit: {
          show: true,
          label: '提交'
        },
        jump: {
          show: true,
          label: '跳转'
        },
        withdraw: {
          show: true,
          label: '撤回'
        },
        expedite: {
          show: true,
          label: '催办'
        },
        restart: {
          show: true,
          label: '重新发起'
        },
        read: {
          show: true,
          label: '知晓'
        },
        after_sign: {
          show: true,
          label: '后加签'
        },
        before_sign: {
          show: true,
          label: '前加签'
        },
        parallel_sign: {
          show: true,
          label: '加签'
        },
        trigger: {
          show: true,
          label: '触发'
        },
        send: {
          show: true,
          label: '发起'
        },
        draft: {
          show: true,
          label: '暂存'
        }
      },
      userTask: {},// 当前用户的任务
      formList: [] // 流程页面需要渲染的表单数据
    }
  },
  computed: {
    processInstanceId() {
      return this.$route.params.id
    },
    userId() {
      let tempUserId = this.$route.params.userId
      if (tempUserId) {
        return tempUserId
      } else {
        return User.getUserId()
      }
    }
  },
  watch: {
    flowInfo: function (newVal, oldVal) {
      this.refreshProcessInfo()
      this.refreshComponentKey = new Date().getTime()
    }
  },
  mounted() {
    // 初始化加载的流程
    this.viewerProcessId = this.processId
    vueApp = this;
    let flowInfoDiv = document.getElementById('flowInfoDiv');
    let tabAreaDiv = document.getElementById('tabAreaDiv');
    let div = tabAreaDiv.getElementsByClassName('el-tabs__nav-scroll')[0];
    div.append(flowInfoDiv)
  },
  methods: {
    getMode(){
      return this.flowInfo?.processInfo?.type || this.mode
    },
    refreshProcessInfo() {
      let configJson = this.flowInfo.configJson;
      if (configJson) {
        this.config = JSON.parse(configJson);
      }
      this.refreshButtons()
      this.findUserTask()
      this.loadFormData()
      document.title = this.flowInfo.processInfo.name
    },
    // 查找当前用户需要办理的任务
    findUserTask() {
      this.userTask = {}
      const activeTasks = this.flowInfo.activeTasks;
      const userId = this.userId;
      if (activeTasks) {
        for (let i = 0; i < activeTasks.length; i++) {
          if(this.userTask.nodeId){
            break
          }
          const temp = activeTasks[i]
          // 直接是办理人了
          if (temp.assignee == userId) {
            this.userTask = temp
          }
          // 检查是否是候选人
          const candidate = temp.candidateUser
          if(candidate){
            if('candidate'==candidate[userId]||'assignee'==candidate[userId]){
              this.userTask = temp
              this.isCandidate = true
            }
          }
        }
      }
      // console.log("userTaksk", this.userTask)
    },
    // 开始加载表单数据
    loadFormData() {
      let task = undefined;
      let uid = this.userId;
      // 如果是已经办过的人，则编辑字段要变为预览状态
      let isUpdateEditToView = false;
      // 优先从集合中查找
      let tasks = this.flowInfo.activeTasks;
      if (uid && tasks && tasks.length > 0) {
        for (let i = 0; i < tasks.length; i++) {
          if (tasks[i].assignee == uid) {
            task = tasks[i]
            break
          }
        }
      }
      // 未找到从高亮集合中查找
      if (!task) {
        let highlights = this.flowInfo.highlights;
        for (let key in highlights) {
          let list = highlights[key]
          for (let i = 0; i < list.length; i++) {
            let obj = list[i]
            if (obj.assignee == uid) {
              task = obj
              isUpdateEditToView = true
              break
            }
          }
        }
      }
      // 如果是超级管理员，则默认地一个节点
      if(!task&&this.flowInfo.processInfo.admin===true){
        if (tasks && tasks.length > 0) {
          task = tasks[0];
        }
      }
      if(!task){
        // 发起人自己可以直接看
        if(!this.isAdmin() && this.userId!=this.flowInfo.processInfo.startUserId){
          this.$notify.error({
            title: '提示',
            message: "你无法查看当前流程数据！！！",
            showClose: false,
          })
          return
        }else{
          isUpdateEditToView = true
        }
      }
      if(this.flowInfo.processInfo.status=='CANCEL' || this.flowInfo.processInfo.status=='COMPLETE'){
        isUpdateEditToView = true
      }
      // 加载多张表单
      let forms = this.flowInfo.forms;
      let loadForms = [];
      let initForm = -1 ;// 默认选中的表单序号
      for (let i = 0; i < forms.length; i++) {
        let form = forms[i];
        let temp = {
          formId: form.formId,
          formName: form.formName,
          dataId: form.dataId,
          hasShow:false,//是否有显示的字段，edit、view都是可显示的字段
          hasEdit:false,//是否有可编辑的字段
          formConfig: [],
          modelId: this.flowInfo.processInstanceId
        }
        if (this.config.nodeConfig && task) {
          let nodeConfig = this.config.nodeConfig[task.nodeId];
          if (nodeConfig) {
            let formConfigs = nodeConfig.formConfig
            for (let j = 0; j < formConfigs.length; j++) {
              if (formConfigs[j].id == form.formId) {
                temp.formConfig = formConfigs[j]
                let fields = temp.formConfig.fields;
                if (fields) {
                  for (let k = 0; k < fields.length; k++) {
                    if (fields[k]['type'] == 'view') {
                      temp.hasShow = true
                    }
                    if (fields[k]['type'] == 'edit') {
                      temp.hasShow = true
                      if (isUpdateEditToView) {
                        fields[k]['type'] = 'view'
                      }else{
                        temp.hasEdit = true
                        this.hasEdit = true
                      }
                    }
                  }
                }
              }
            }
          }
        }else{
          // 如果是知会或者抄送，则默认可看
          temp.hasShow = true
          temp.modelId = this.flowInfo.processInfo.parentProcessId
          let fields = form.fields;
          if (fields) {
            for (let k = 0; k < fields.length; k++) {
              fields[k]['type'] = 'view'
            }
          }
          temp.formConfig = form
        }
        // 有编辑的表单可显示
        // 有显示的字段并且有数据的可显示，过滤空表单
        if(temp.hasEdit || (temp.hasShow && temp.dataId)){
          if(temp.hasEdit){
            initForm=loadForms.length
          }
          loadForms.push(temp)
        }
      }
      this.formList = loadForms
      // 初始化选中，需要填写的表单
      if(initForm>0){
        this.tabName='form'+initForm
      }
      if(this.formList.length==0){
        this.tabName='flow'
      }
    },
    // 处理那些按钮显示，或者按钮显示成什么名称
    refreshButtons() {
      // 查找当前办理人，如果没找到则模式人第一个
      let tasks = this.flowInfo.activeTasks;
      if (this.config && tasks && tasks.length > 0) {
        let task = tasks[0];
        let uid = this.userId;
        if (uid) {
          for (let i = 0; i < tasks.length; i++) {
            if (tasks[i].assignee == uid) {
              task = tasks[i]
            }
          }
        }
        // 把按钮的新文本设置到界面显示
        if (this.config.nodeConfig) {
          let nodeConfig = this.config.nodeConfig[task.nodeId];
          if (nodeConfig) {
            let buttonsConfigs = nodeConfig.buttonConfig;
            if (buttonsConfigs) {
              for (let i = 0; i < buttonsConfigs.length; i++) {
                let buttonConfig = buttonsConfigs[i]
                let button = this.buttons[buttonConfig.value];
                if (button) {
                  button.show = buttonConfig.show
                  button.label = buttonConfig.newLabel || buttonConfig.label
                }
              }
            }
          }
        }
      }
    },
    formattedDate(time) {
      const date = new Date(time);
      const options = {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric',
      };
      return date.toLocaleString(undefined, options);
    },
    // 调用表单处理
    async handlerFormSend() {
      let editCount = 0;
      let successCount = 0;
      //  通知后端那些表单有数据变化
      let formIds = '';
      for (let i = 0; i < this.formList.length; i++) {
        let formConfig = this.formList[i]
        if (formConfig.hasEdit) { // 如果表单有编辑内容
          editCount++;
          let name = 'formDataArea' + i
          let formDataArea = this.$refs[name][0]
          let res = await formDataArea.handleSend()
          if (res.success) {
            if(formIds!=''){
              formIds+=','
            }
            formIds+=formConfig.formId
            successCount++;
          } else {
            this.showMessage(this.buttons.send.label,i, formConfig, res)
            break
          }
        }
      }

      // 表单都提交成功，才执行后续动作
      if (successCount === editCount) {
        const params = {
          formId: formIds,
          modelId: this.flowInfo.processInstanceId
        }
        let pas = await processActionSend(params, {});
        if (pas.success) {
          this.hasEdit=false
          this.$notify.success({
            title: '提示',
            message: this.buttons.send.label + '成功',
            showClose: false,
          })
          if (pas.data.processInstanceId) {
            this.chanageProcessId(pas.data.processInstanceId)
          }
        } else {
          this.$notify.error({
            title: '提示',
            message: this.buttons.send.label + '失败：' + pas.errorMessage,
            showClose: false,
          })
        }
      }
    },
    // 调用表单处理
    async handlerFormDraft() {
      let editCount = 0;
      let successCount = 0;
      for (let i = 0; i < this.formList.length; i++) {
        let formConfig = this.formList[i]
        if (formConfig.hasEdit) { // 如果表单有编辑内容
          editCount++;
          let name = 'formDataArea' + i
          let formDataArea = this.$refs[name][0]
          let res = await formDataArea.handleDraft()
          if (res.success) {
            successCount++;
          }else{
            this.showMessage(this.buttons.draft.label,i,formConfig,res)
            break
          }
        }
      }

      if(successCount===editCount){
        this.$notify.success({
          title: '提示',
          message: this.buttons.draft.label + '成功',
          showClose: false,
        })
      }
    },
    showMessage(label,i,formConfig,res){
      this.tabName='form'+i
      this.$notify.error({
        title: '提示',
        message: label+'表单[' + formConfig.formName + '] 失败：' + res.errorMessage,
        showClose: false,
      })
    },
    // 流程数据通知方法
    flowDataNotice(data) {
      this.flowInfo = data
    },
    // 解决流程初始化不显示的问题
    handleTabChange(tab) {
      if(tab==='flow'){
        this.$refs.viewer.refreshCanvas()
      }
    },
    // 重新刷新数据
    refreshData() {
      this.flowInfo.processInstanceId=''
      this.$nextTick(() => {
        this.$refs.viewer.initData()
      })
    },
    chanageProcessId(id){
      this.flowInfo.processInstanceId=''
      this.viewerProcessId = id;
    },
    // 重新发起
    async handlerActionRestart() {
      const params = {
        operatorName: this.buttons.expedite.label,
        processInstanceId: this.flowInfo.processInstanceId
      }
      let pas = await processActionRestart(params, {});
      if (pas.success) {
        this.$notify.success({
          title: '提示',
          message: this.buttons.restart.label + '成功',
          showClose: false,
        })
        this.chanageProcessId(pas.data.processInstanceId)
      } else {
        this.$notify.error({
          title: '提示',
          message: this.buttons.restart.label + '失败：' + pas.errorMessage,
          showClose: false,
        })
      }
    },
    // 催办
    async handlerActionExpedite() {
      const params = {
        operatorName: this.buttons.expedite.label,
        processInstanceId: this.flowInfo.processInstanceId
      }
      let pas = await processActionExpedite(params, {});
      if (pas.success) {
        this.$notify.success({
          title: '提示',
          message: this.buttons.expedite.label + '成功',
          showClose: false,
        })
      } else {
        this.$notify.error({
          title: '提示',
          message: this.buttons.expedite.label + '失败：' + pas.errorMessage,
          showClose: false,
        })
      }
    },
    // 提交数据
    async handlerActionSubmit(data, messageAuth) {
      let editCount = 0;
      let successCount = 0;
      //  通知后端那些表单有数据变化
      let formIds = '';
      for (let i = 0; i < this.formList.length; i++) {
        let formConfig = this.formList[i]
        if (formConfig.hasEdit) { // 如果表单有编辑内容
          editCount++;
          let name = 'formDataArea' + i
          let formDataArea = this.$refs[name][0]
          let res = await formDataArea.handleSend()
          if (res.success) {
            if (formIds != '') {
              formIds += ','
            }
            formIds += formConfig.formId
            successCount++;
          } else {
            this.showMessage(this.buttons.submit.label, i, formConfig, res)
            break
          }
        }
      }

      // 表单都提交成功，才执行后续动作
      if (successCount === editCount) {
        const params = {
          formId: formIds,
          operatorName: this.buttons.submit.label,
          modelId: this.flowInfo.processInstanceId,
          taskId: this.userTask.taskId
        }
        let pas = await processActionSubmit(params, {});
        if (pas.success) {
          this.hasEdit = false
          this.$notify.success({
            title: '提示',
            message: this.buttons.submit.label + '成功',
            showClose: false,
          })
          this.refreshData()
        } else {
          this.$notify.error({
            title: '提示',
            message: this.buttons.submit.label + '失败：' + pas.errorMessage,
            showClose: false,
          })
        }
      }
    },
    // 同意
    handlerApprove() {
      this.$refs.approve.show()
    },
    handlerActionApprove(data, messageAuth) {
      return processActionApprove(data, messageAuth)
    },
    // 不统一
    handlerReject() {
      this.$refs.reject.show()
    },
    handlerActionReject(data, messageAuth) {
      return processActionReject(data, messageAuth)
    },
    // 抄送
    handlerCc() {
      this.$refs.cc.show()
    },
    handlerActionCc(data, messageAuth) {
      return processActionCc(data, messageAuth)
    },
    // 前加签
    handlerBeforeSign() {
      this.$refs.beforeSign.show()
    },
    handlerActionBeforeSign(data, messageAuth) {
      return processActionBeforeSign(data, messageAuth)
    },
    // 后加签
    handlerAfterSign() {
      this.$refs.afterSign.show()
    },
    handlerActionAfterSign(data, messageAuth) {
      return processActionAfterSign(data, messageAuth)
    },
    // 并加签
    handlerParallelSign() {
      this.$refs.parallelSign.show()
    },
    handlerActionParallelSign(data, messageAuth) {
      return handlerActionParallelSign(data, messageAuth)
    },
    // 知会
    handlerNotification() {
      this.$refs.notification.show()
    },
    handlerActionNotification(data, messageAuth) {
      return processActionNotification(data, messageAuth)
    },
    // 知晓
    handlerRead() {
      this.$refs.read.show()
    },
    handlerActionRead(data, messageAuth) {
      return processActionRead(data, messageAuth)
    },
    // 认领
    handlerClaim() {
      this.$refs.claim.show()
    },
    handlerActionClaim(data, messageAuth) {
      return processActionClaim(data, messageAuth)
    },
    // 归还
    handlerUnclaim() {
      this.$refs.unclaim.show()
    },
    handlerActionUnclaim(data, messageAuth) {
      return processActionUnclaim(data, messageAuth)
    },
    // 委派
    handlerDelegate() {
      this.$refs.delegate.show()
    },
    handlerActionDelegate(data, messageAuth) {
      return processActionDelegate(data, messageAuth)
    },
    // 回退
    handlerRollback() {
      this.$refs.rollback.show()
    },
    handlerActionRollback(data, messageAuth) {
      return processActionRollback(data, messageAuth)
    },
    // 取消
    handlerCancel() {
      this.$refs.cancel.show()
    },
    handlerActionCancel(data, messageAuth) {
      return processActionCancel(data, messageAuth)
    },
    // 跳转
    handlerJump() {
      this.$refs.jump.show()
    },
    handlerActionJump(data, messageAuth) {
      return processActionJump(data, messageAuth)
    },
    // 撤回
    handlerWithdraw() {
      this.$refs.withdraw.show()
    },
    handlerActionWithdraw(data, messageAuth) {
      return processActionWithdraw(data, messageAuth)
    },
    // 触发
    handlerTrigger() {
      this.$refs.trigger.show()
    },
    handlerActionTrigger(data, messageAuth) {
      return processActionTrigger(data, messageAuth)
    },
    // =========================== 计算每个按钮的显示情况 =====================================
    isAdmin() { //  是否是管理员
      return true;
      // return this.flowInfo.processInfo.admin
    },
    isEnd() { //  是否结束
      return this.flowInfo.processInfo.status=='CANCEL' || this.flowInfo.processInfo.status=='COMPLETE'
    },
    isPre() { // 是否是预备发起流程
      const processInfo = this.flowInfo.processInfo;
      if (processInfo.startUserId != this.userId) {
        return false
      }
      const status = processInfo.status || ''
      return status == 'PREPARE'
    },
    isStarterAndActive() { //  是否是发起人操作,并且是激活炒作
      const processInfo = this.flowInfo.processInfo;
      if (processInfo.startUserId != this.userId) {
        return false
      }
      return processInfo.status == 'ACTIVE'
    },
    isStarterAndComplate() { //  是否是发起人操作,并且是完成状态
      const processInfo = this.flowInfo.processInfo;
      if (processInfo.startUserId != this.userId) {
        return false
      }
      return this.isEnd()
    },
    isHandler() { // 是否是办理人节点
      // 如果存在编辑的内容，则不是办理节点
      if (this.userTask.assignee != this.userId) {
        return false
      }
      const temp = this.userTask.nodeType || ''
      return !this.hasEdit && (temp == 'MULTIPLE_PARALLEL' || temp == 'MULTIPLE_SEQUENTIAL' || temp == 'SINGLE_APPROVE')
    },
    isParallelHandler() { // 是否是并行多人办理节点
      if (this.userTask.assignee != this.userId) {
        return false
      }
      const temp = this.userTask.nodeType || ''
      return temp == 'MULTIPLE_PARALLEL'
    },
    isSequentialHandler() { // 是否是串行多人办理节点
      if (this.userTask.assignee != this.userId) {
        return false
      }
      const temp = this.userTask.nodeType || ''
      return temp == 'MULTIPLE_SEQUENTIAL'
    },
    isNotificationHandler() { // 是否是知会
      const temp = this.userTask.nodeType || ''
      return temp == 'NOTIFICATION'
    },
    isCC() { // 是否是抄送
      const temp = this.userTask.nodeType || ''
      return temp == 'CC'
    },
    approveShow() {
      return this.isHandler() && this.buttons.approve.show
    },
    rejectShow() {
      return this.isHandler() && this.buttons.reject.show
    },
    rollbackShow() {
      return this.isHandler() && this.buttons.rollback.show
    },
    delegateShow() {
      return this.isHandler() && this.buttons.delegate.show
    },
    ccShow() {
      return (this.isHandler() || (this.isStarterAndComplate() && !this.isNotificationHandler() && !this.isCC())) && this.buttons.cc.show
    },
    notificationShow() {
      return (this.isHandler() || (this.isStarterAndComplate() && !this.isNotificationHandler() && !this.isCC())) && this.buttons.notification.show
    },
    readShow() {
      return this.isNotificationHandler() && this.buttons.read.show
    },
    claimShow() {
      return this.isCandidate && !this.userTask.assignee && this.buttons.claim.show
    },
    unclaimShow() {
      return this.isCandidate && this.userTask.assignee==this.userId  && this.buttons.unclaim.show
    },
    beforeSignShow() {
      return this.isSequentialHandler() && this.buttons.before_sign.show
    },
    afterSignShow() {
      return this.isSequentialHandler() && this.buttons.after_sign.show
    },
    parallelSignShow() {
      return this.isParallelHandler() && this.buttons.parallel_sign.show
    },
    cancelShow() {
      return this.isStarterAndActive() && this.buttons.cancel.show
    },
    jumpShow() {
      return this.isAdmin() && !this.isEnd() && !this.isPre() && this.buttons.jump.show
    },
    restartShow(){
      return this.isStarterAndComplate() && !this.isNotificationHandler() && !this.isCC()  && this.buttons.restart.show
    },
    expediteShow(){
      return this.isStarterAndActive() && !this.userTask.assignee && this.buttons.expedite.show
    },
    withdrawShow() {
      return this.isStarterAndActive() && this.buttons.withdraw.show
    },
    triggerShow() {
      return this.isAdmin() && !this.isEnd() && !this.isPre() && this.buttons.trigger.show
    },
    sendShow() {
      return this.isPre() && this.buttons.send.show
    },
    draftShow() {
      return this.hasEdit && this.buttons.draft.show
    },
    submitShow() {
      return this.hasEdit && !this.isPre() && this.buttons.submit.show
    }
  }
}

</script>
<style scoped>
@import '@/css/base.css';
</style>
